package com.mini.controller;


import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSONObject;
import com.mini.es.model.EsBusinessStudentBigLessonXcx;
import com.mini.es.service.EsBusinessStudentBigLessonXcxService;
import com.mini.es.service.EsBusinessStudentOrderInfoService;
import com.mini.mysql.model.AttnClassInfo;
import com.mini.mysql.model.AttnStudentOrder;
import com.mini.mysql.model.BusinessStudentBigLessonXcx;
import com.mini.mysql.model.Dept;
import com.mini.mysql.service.BaseService;
import com.mini.mysql.service.ClassService;
import com.mini.mysql.service.MnsService;
import com.mini.vo.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.task.AsyncTaskExecutor;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.*;

import java.math.BigInteger;
import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/student/bigLesson")
@Slf4j
@Api(tags = "大课相关")
public class BigLessonController extends BaseController {


    @Autowired
    private BaseService baseService;

    @Autowired
    private MnsService mnsService;

    @Autowired
    private ClassService classService;

    @Autowired
    private EsBusinessStudentBigLessonXcxService esBusinessStudentBigLessonXcxService;


    @ApiOperation(value = "大课学员列表  ")
    @PostMapping(value = "/order/list")
    public BusinessResult<PageResultVO<BigLessonOrderPageVO>> orderList(@ApiParam(value = "token", required = true) @RequestHeader String Authorization,
                                                                        @RequestBody BigLessonOrderCondition condition) {

        Long loginUserId = this.getLoginUserId(Authorization);
        log.info("大课学员列表查询-loginUser={}, param={}", loginUserId, JSONObject.toJSONString(condition));
        //判断运营专员角色等
        conditionHandler(Authorization, condition);
        Page<EsBusinessStudentBigLessonXcx> pageResult = esBusinessStudentBigLessonXcxService.pageByCondition(condition);
        List<EsBusinessStudentBigLessonXcx> content = pageResult.getContent();
        List<BigLessonOrderPageVO> bigLessonOrderPageVOList = new ArrayList<>();
        Set<String> relatedKeySet = content.stream().filter(esBusinessStudentBigLessonXcx -> Objects.nonNull(esBusinessStudentBigLessonXcx.getRelatedKey())).map(esBusinessStudentBigLessonXcx -> esBusinessStudentBigLessonXcx.getRelatedKey()).collect(Collectors.toSet());
        content = baseService.decryptObjs(content);

        Map<String, EsBusinessStudentBigLessonXcx> xcxMap = new HashMap<>();
        if(CollectionUtils.isNotEmpty(relatedKeySet)){
            List<EsBusinessStudentBigLessonXcx> depositList =
                    esBusinessStudentBigLessonXcxService.findDeposit(relatedKeySet, BusinessStudentBigLessonXcx.OrderState.PAY_FINISH.getState(), BusinessStudentBigLessonXcx.OrderDeposiType.ORDER_PDEPOSIT.getType().intValue());
            xcxMap = depositList.stream().collect(Collectors.toMap(o -> o.getRelatedKey(), o -> o, (o1, o2) -> this.compareTo(o1, o2)));
        }

        Map<String, EsBusinessStudentBigLessonXcx> finalXcxMap = xcxMap;
        content.forEach(esBusinessStudentBigLessonXcx -> {
            BigLessonOrderPageVO pageVO = BigLessonOrderPageVO.from(esBusinessStudentBigLessonXcx);
            bigLessonOrderPageVOList.add(pageVO);

            if(StringUtils.isNotEmpty(pageVO.getBoRelatedKey()) && Objects.nonNull(pageVO.getBoOrderDepositType()) && pageVO.getBoOrderDepositType().intValue() == BusinessStudentBigLessonXcx.OrderDeposiType.ORDER_BALANCE.getType().intValue()){
                EsBusinessStudentBigLessonXcx bigLessonXcx = finalXcxMap.get(pageVO.getBoRelatedKey());
                if(Objects.nonNull(bigLessonXcx)){
                    //查询定金订单
                    pageVO.setBoDepositOrderNo(bigLessonXcx.getOrderNo());
                    pageVO.setBoDepositPayTime(bigLessonXcx.getPayFinishTime());
                    pageVO.setBoDepositPayAmount(bigLessonXcx.getPayAmount());
                    pageVO.setBoDepositLessonId(bigLessonXcx.getLessonId());
                    pageVO.setBoDepositLessonName(bigLessonXcx.getLessonName());
                }
            }
        });
        // 组织
        this.orgNameHandler(bigLessonOrderPageVOList);
        //班次
        if(condition.getAttachClassInfo()!= null && condition.getAttachClassInfo() == 1){
            this.classInfoHandler(bigLessonOrderPageVOList);
        }

        PageResultVO<BigLessonOrderPageVO> result = new PageResultVO<>(pageResult.getTotalElements(), bigLessonOrderPageVOList);

        return BusinessResult.createSuccessInstance(result);
    }

    private void classInfoHandler(Collection<BigLessonOrderPageVO> list){
        if(org.springframework.util.CollectionUtils.isEmpty(list)){
            return;
        }

        List<String> orderNos = list.stream()
                .filter(o->o!=null && org.apache.commons.lang.StringUtils.isNotBlank(o.getMoOrderNo()))
                .map(BigLessonOrderPageVO::getMoOrderNo)
                .collect(Collectors.toList());
        if(CollectionUtil.isEmpty(orderNos)){
            return;
        }

        List<AttnStudentOrder> classOrders = this.classService.getClassOrder(orderNos);
        if(org.springframework.util.CollectionUtils.isEmpty(classOrders)){
            return;
        }

        Map<String, Long> orderClassIdMap = classOrders.stream().collect(Collectors.toMap(AttnStudentOrder::getOrderNo, o->o.getClassId(), (o1,o2)->o1));

        Set<Long> classIds = new HashSet<>(orderClassIdMap.values());

        Map<Long, AttnClassInfo> map = classService.mapClassSimpleInfo(classIds);
        if(map == null){
            return;
        }

        list.stream().forEach(o->{
            if(org.apache.commons.lang.StringUtils.isNotBlank(o.getMoOrderNo())){
                Long classId = orderClassIdMap.get(o.getMoOrderNo());
                AttnClassInfo classInfo = map.get(classId);
                if(classInfo != null){
                    o.setMoClassName(classInfo.getClassName());
                }

            }
        });
    }

    private EsBusinessStudentBigLessonXcx compareTo(EsBusinessStudentBigLessonXcx o1, EsBusinessStudentBigLessonXcx o2){
        if (o1 == null){
            return o2;
        }
        if(o2 == null){
            return o1;
        }
        if(o1.getOrderCreateTime() == null){
            return o2;
        }
        if(o2.getOrderCreateTime() == null){
            return o1;
        }

        if(o1.getOrderCreateTime().after(o2.getOrderCreateTime())){
            return o1;
        }
        return o2;
    }


    private void conditionHandler(String Authorization, BigLessonOrderCondition condition) {

        Long loginUserId = this.getLoginUserId(Authorization);

        boolean zhuanyuan = miniAdminService.hasYunyingzhuanyuanPermission(Authorization);

        //组织架构：如果是运营专员，且org未选择，则设置teacherId
        if (zhuanyuan
                && StringUtils.isBlank(condition.getLevel())
                && condition.getOrgId() == null
                && condition.getYunying() == null) {

            condition.setTeacherId(loginUserId);
        }


        //keyword
        if (org.apache.commons.lang.StringUtils.isNotBlank(condition.getKeyword())) {
            condition.setPhoneNo(baseService.encryptField(condition.getKeyword()));
        }
    }


    private void orgNameHandler(Collection<BigLessonOrderPageVO> list){
        if(org.springframework.util.CollectionUtils.isEmpty(list)){
            return;
        }

        Set<Long> teacherIds = list.stream().filter(o -> o.getYyTeacherId() != null).map(BigLessonOrderPageVO :: getYyTeacherId).collect(Collectors.toSet());
        if(org.springframework.util.CollectionUtils.isEmpty(teacherIds)){
            return;
        }

        Map<Long, UserVO> teacherMap = new HashMap<>();
        Map<Long, String> deptNameMap = new HashMap<>();
        for(BigLessonOrderPageVO vo : list){
            Long teacherId = vo.getYyTeacherId();
            if(teacherId != null && teacherId != 0L){
                UserVO teacher = teacherMap.get(teacherId);
                if(teacher == null){
                    teacher = miniAdminService.getUserSimpleInfo(teacherId);
                }
                if(teacher != null){
                    teacherMap.put(teacherId, teacher);

                    vo.setYyTeacherEmail(teacher.getEmail());
                    vo.setYyTeacherUsername(teacher.getUsername());

                    if(teacher.getFullDept() != null){
                        teacherMap.put(teacherId, teacher);
                        FullDeptVo fullDeptVo = teacher.getFullDept();
                        vo.setYyTeacherName(teacher.getNickname());
                        vo.setYyGroupId(fullDeptVo.getOgId());
                        vo.setYyGroupName(fullDeptVo.getOgName());
                        vo.setYyDeptId(fullDeptVo.getOdId());
                        vo.setYyDeptName(fullDeptVo.getOdName());
                        vo.setYyStudioId(fullDeptVo.getWorkRoomId());
                        vo.setYyStudioName(fullDeptVo.getWorkRoomName());
                        vo.setYySkuOrgId(fullDeptVo.getSkuId());
                        vo.setYySkuOrgName(fullDeptVo.getSkuName());
                        vo.setYyBuId(fullDeptVo.getDeptLevel3Id());
                        vo.setYyBuName(fullDeptVo.getDeptLevel3Name());
                    }

                }
            }else {
                //处理设置大课归属，但是只设置到组织的那部分
                if(vo.getYyGroupId() != null && vo.getYyGroupId() != 0L){
                    String name = deptNameMap.get(vo.getYyGroupId());
                    if(org.apache.commons.lang.StringUtils.isBlank(name)){
                        name = miniAdminService.getDeptName(vo.getYyGroupId());
                    }
                    if(org.apache.commons.lang.StringUtils.isNotBlank(name)){
                        vo.setYyGroupName(name);
                        deptNameMap.put(vo.getYyGroupId(), name);
                    }

                }

                if(vo.getYyDeptId() != null && vo.getYyDeptId()!=0){
                    String name = deptNameMap.get(vo.getYyDeptId());
                    if(org.apache.commons.lang.StringUtils.isBlank(name)){
                        name = miniAdminService.getDeptName(vo.getYyDeptId());
                    }
                    if(org.apache.commons.lang.StringUtils.isNotBlank(name)){
                        vo.setYyDeptName(name);
                        deptNameMap.put(vo.getYyDeptId(), name);
                    }

                }

                if(vo.getYyStudioId() != null && vo.getYyStudioId()!=0){
                    String name = deptNameMap.get(vo.getYyStudioId());
                    if(org.apache.commons.lang.StringUtils.isBlank(name)){
                        name = miniAdminService.getDeptName(vo.getYyStudioId());
                    }
                    if(org.apache.commons.lang.StringUtils.isNotBlank(name)){
                        vo.setYyStudioName(name);
                        deptNameMap.put(vo.getYyStudioId(), name);
                    }

                }

            }

        }

    }
}
